package com.junzhiit.nengji.shop.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.junzhiit.nengji.bo.GoodsInfoBO;
import com.junzhiit.nengji.dao.SystemTypeDAO;
import com.junzhiit.nengji.model.SystemType;
import com.junzhiit.nengji.model.enums.ShopIsPlatform;
import com.junzhiit.nengji.shop.service.SystemTypeService;
import com.junzhiit.nengji.shop.web.exception.SystemTypeIsExistException;
import com.junzhiit.nengji.shop.web.exception.SystemTypeNotFoundException;
import com.junzhiit.nengji.shop.web.util.Constants;
import com.junzhiit.nengji.shop.web.util.FileUtil;
import com.junzhiit.nengji.shop.web.util.OrderNumberUtils;
import com.junzhiit.nengji.shop.web.vo.ResultVO;
import com.junzhiit.nengji.shop.web.vo.SystemTypeConditionVO;
import com.junzhiit.nengji.shop.web.vo.SystemTypeEditVO;
import com.junzhiit.nengji.shop.web.vo.SystemTypeGoodsVO;
import com.junzhiit.nengji.shop.web.vo.SystemTypeVO;

@Service
public class SystemTypeServiceImpl extends BaseServiceImpl implements SystemTypeService {

	@Autowired
	private SystemTypeDAO systemTypeDAO;
	
	@Value("${upload.temp}")
	private String uploadPath;

	@Value("${upload.mall.goods.type}")
	private String typePath;

	@Override
	public ResultVO findAll() {
		ResultVO result = new ResultVO();
		List<SystemType> sourceList = source();
		result.setData(sourceList);
		return result;
	}
	
	@Override
	public ResultVO findAllName() {
		ResultVO result = new ResultVO();
		List<SystemTypeGoodsVO> aimsList = new ArrayList<SystemTypeGoodsVO>();
		List<SystemType> sourceList = source();
		for(SystemType info:sourceList){
			SystemTypeGoodsVO goodsvo = new SystemTypeGoodsVO();
			BeanUtils.copyProperties(info, goodsvo);
			aimsList.add(goodsvo);
		}
		result.setData(aimsList);
		sourceList.clear();
		return result;
	}

	@Override
	public ResultVO findAllGrading() {
		ResultVO result = new ResultVO();
		List<SystemType> sourceList = source();
		List<SystemTypeVO> aimsList = new ArrayList<SystemTypeVO>();
		if (!sourceList.isEmpty()) {
			tree(aimsList, sourceList, Constants.ROOT_VALUE);
		}
		result.setData(aimsList);
		return result;
	}

	@Override
	public ResultVO findAllNameGrading() {
		ResultVO result = new ResultVO();
		List<SystemType> sourceList = source();
		List<SystemTypeVO> aimsList = new ArrayList<SystemTypeVO>();
		List<SystemTypeGoodsVO> aimsGoodsList = new ArrayList<SystemTypeGoodsVO>();
		if (!sourceList.isEmpty()) {
			tree(aimsList, sourceList, Constants.ROOT_VALUE);
		}
		if(!aimsList.isEmpty()){
			nameGradingRecursive(aimsGoodsList,aimsList);
		}
		result.setData(aimsGoodsList);
		return result;
	}
	
	private List<SystemType> source(){
		List<SystemType> sourceList = systemTypeDAO.findAll();
		return sourceList;
	}
	
	private void nameGradingRecursive(List<SystemTypeGoodsVO> aimsList,List<SystemTypeVO> sourceList){
		for(SystemTypeVO info:sourceList){
			SystemTypeGoodsVO goodsvo = new SystemTypeGoodsVO();
			BeanUtils.copyProperties(info, goodsvo);
			aimsList.add(goodsvo);
			goodsvo.setChildrenGoods(new ArrayList<SystemTypeGoodsVO>());
			if(info.getChildren() !=null && info.getChildren().size()>0){
				nameGradingRecursive(goodsvo.getChildrenGoods(),info.getChildren());
			}
		}
	}
	
	private void tree(List<SystemTypeVO> aimsList, List<SystemType> sourceList, String parentId) {
		for(int i = 0;i<sourceList.size();i++){
			SystemType type = sourceList.get(i);
			if (parentId.equals(type.getId())) {
				SystemTypeVO typeVO = new SystemTypeVO();
				BeanUtils.copyProperties(type, typeVO);
				aimsList.add(typeVO);
				sourceList.remove(type);
				typeVO.setChildren(new ArrayList<SystemTypeVO>());
				tree(typeVO.getChildren(), sourceList, typeVO.getParentId());
				break;
			} else if (parentId.equals(type.getParentId())) {
				SystemTypeVO typeVO = new SystemTypeVO();
				BeanUtils.copyProperties(type, typeVO);
				aimsList.add(typeVO);
				sourceList.remove(type);
				i = -1;
				typeVO.setChildren(new ArrayList<SystemTypeVO>());
				tree(typeVO.getChildren(), sourceList, typeVO.getId());
			}
		}
	}

	@Override
	public ResultVO getAllByCondition(SystemTypeConditionVO typevo) {
		ResultVO result = new ResultVO();
		SystemType type = new SystemType();
		BeanUtils.copyProperties(typevo, type);
		List<SystemType> sourceList = systemTypeDAO.getAllByCondition(type);
		List<SystemTypeVO> aimsList = new ArrayList<SystemTypeVO>();
		if (!sourceList.isEmpty()) {
			if (StringUtils.isNotBlank(type.getId())) {
				tree(aimsList, sourceList, type.getId());
			} else {
				if (StringUtils.isNotBlank(type.getName())) {
					for (SystemType info : sourceList) {
						tree(aimsList, sourceList, info.getParentId());
					}
				} else {
					for (SystemType info : sourceList) {
						SystemTypeVO typeVO = new SystemTypeVO();
						BeanUtils.copyProperties(info, typeVO);
						aimsList.add(typeVO);
					}
				}
			}
		}
		result.setData(aimsList);
		return result;
	}

	@Override
	public ResultVO getMaxCode(String parentId) {
		ResultVO result = new ResultVO();
		result.setData(systemTypeDAO.getMaxCode(parentId));
		return result;
	}

	@Override
	public ResultVO getMaxFullCode(String parentId) {
		ResultVO result = new ResultVO();
		result.setData(systemTypeDAO.getMaxFullCode(parentId));
		return result;
	}

	@Override
	public ResultVO getMaxSort(String parentId) {
		ResultVO result = new ResultVO();
		result.setData(systemTypeDAO.getMaxSort(parentId));
		return result;
	}

	@Override
	public ResultVO add(SystemType infoCategory) {
		ResultVO result = new ResultVO();
		int con = systemTypeDAO.getInfoCategoryExist(infoCategory);
		if (con > 0) {
			throw new SystemTypeIsExistException("该分类名字已经存在");
		}
		SystemType parentInfo = systemTypeDAO.query(infoCategory.getParentId());
		String code = systemTypeDAO.getMaxCode(infoCategory.getParentId());
		code = getTypeCode(code);
		String fullCode = null;
		String fullName = null;
		int sort = 1;
		int level = 1;
		if (parentInfo != null) {
			level = parentInfo.getLevel() + 1;
			String parentfullName = parentInfo.getFullName();

			String maxcode = systemTypeDAO.getMaxFullCode(infoCategory.getParentId());
			fullCode = parentInfo.getFullCode() + getTypeFullCode(OrderNumberUtils.TYPE_NUMBER_PREFIX, maxcode);

			sort = systemTypeDAO.getMaxSort(infoCategory.getParentId()) + Constants.TYPE_SORT_ONE;

			if (StringUtils.isBlank(parentfullName)) {
				throw new SystemTypeNotFoundException("顶级类未找到");
			}

			fullName = parentfullName + Constants.TYPE_FULLNAME_SEPARATOR + infoCategory.getName();
		} else {
			fullName = infoCategory.getName();
			sort = systemTypeDAO.getMaxSort(Constants.ROOT_VALUE) + Constants.TYPE_SORT_ONE;
			fullCode = systemTypeDAO.getMaxFullCode(Constants.ROOT_VALUE);
			fullCode = getTypeFullCode(OrderNumberUtils.TYPE_NUMBER_PREFIX, fullCode);
		}
		infoCategory.setLevel(level);
		infoCategory.setFullCode(fullCode);
		infoCategory.setFullName(fullName);
		infoCategory.setSort(sort);
		infoCategory.setCode(code);
		result.setData(systemTypeDAO.insert(infoCategory));
		return result;
	}

	private String getTypeCode(String maxCode) {
		int codeValue = 1;
		if (StringUtils.isNotBlank(maxCode)) {
			int currentMaxCode = Integer.valueOf(maxCode);
			codeValue += currentMaxCode;
		}
		String code = OrderNumberUtils.getSystemCode("", codeValue);
		return code;
	}

	private String getTypeFullCode(String prefix, String maxCode) {
		int codeValue = 1;
		if (StringUtils.isNotBlank(maxCode)) {
			int currentMaxCode = Integer.valueOf(maxCode.substring(maxCode.length() - 3, maxCode.length()));
			codeValue += currentMaxCode;
		}
		String code = OrderNumberUtils.getSystemCode(prefix, codeValue);
		return code;
	}

	@Override
	public ResultVO delete(String id) {
		ResultVO result = new ResultVO();
		SystemType infoCategory = systemTypeDAO.query(id);
		if (infoCategory == null) {
			throw new SystemTypeNotFoundException("该分类未找到");
		}
		boolean boo = systemTypeDAO.updateToDelete(id);
		if (boo) {
			List<SystemType> info = systemTypeDAO.getChildId(id);
			List<String> idsArr = new ArrayList<String>();
			deleteRecursive(idsArr, info);
			String[] ids = idsArr.toArray(new String[] {});
			if (ids.length > 0 && ids != null) {
				boolean childrenflag = systemTypeDAO.batchUpdateToDelete(ids);
				result.setData(childrenflag);
			}
		}
		return result;
	}

	private void deleteRecursive(List<String> idsArr, List<SystemType> info) {
		if (!info.isEmpty()) {
			for (int i = 0;i<info.size();i++) {
				SystemType item = info.get(i);
				String childrenId = item.getId();
				idsArr.add(childrenId);
				info.remove(item);
				List<SystemType> childrenTypes = systemTypeDAO.getChildId(childrenId);
				if(childrenTypes.size()>0){
					deleteRecursive(idsArr, childrenTypes);
				}
			}
			info.clear();
		}
	}

	@Override
	public ResultVO update(SystemType infoCategory) {
		ResultVO result = new ResultVO();

		SystemType type = systemTypeDAO.query(infoCategory.getId());
		if (type == null) {
			throw new SystemTypeNotFoundException("该分类未找到");
		}

		String name = infoCategory.getName();
		type.setName(name);
		int count = systemTypeDAO.getInfoCategoryExist(type);
		if (count > 0) {
			throw new SystemTypeIsExistException("该分类名字已经存在");
		}

		// 更新该分类full_name
		String FullName = type.getFullName();
		String NewfullName = getNewFullName(FullName, name);
		type.setImgUrl(infoCategory.getImgUrl());
		type.setFullName(NewfullName);

		systemTypeDAO.update(type);

		// 更新该分类下子类的full_name
		List<SystemType> typeResuls = new ArrayList<SystemType>();

		switch (type.getLevel()) {
		case 1:
			List<SystemType> types = systemTypeDAO.getChild(type.getId());

			for (SystemType t : types) {
				String fullName = t.getFullName();
				String NewFullName = getNewFullNameByFrist(fullName, name);
				t.setFullName(NewFullName);
				List<SystemType> typeChilds = systemTypeDAO.getChild(t.getId());

				for (SystemType tChild : typeChilds) {
					String ChildfullName = tChild.getFullName();
					String ChildNewFullName = getNewFullNameByFrist(ChildfullName, name);
					tChild.setFullName(ChildNewFullName);
				}

				typeResuls.addAll(typeChilds);
			}

			typeResuls.addAll(types);

			break;
		case 2:
			List<SystemType> typeseconds = systemTypeDAO.getChild(type.getId());
			for (SystemType t : typeseconds) {
				String fullName = t.getFullName();
				String NewFullName = getNewFullNameBySecond(fullName, name);
				t.setFullName(NewFullName);
			}
			typeResuls.addAll(typeseconds);

			break;
		default:
			break;
		}

		systemTypeDAO.batchUpdate(typeResuls,true);
		return result;
	}
	
	private String getNewFullName(String fullName, String name) {
		int beginindex = fullName.lastIndexOf(">") < 0 ? 0 : fullName.lastIndexOf(">") + 1;
		String old = fullName.substring(beginindex, fullName.length());
		String NewFullName = fullName.replace(old, name);
		return NewFullName;
	}

	private String getNewFullNameByFrist(String fullName, String name) {
		int beginindex = fullName.indexOf(">") < 0 ? 0 : fullName.indexOf(">");
		String old = fullName.substring(0, beginindex);
		String NewFullName = fullName.replaceFirst(old, name);
		return NewFullName;
	}

	private String getNewFullNameBySecond(String fullName, String name) {
		int beginIndex = fullName.indexOf(">") < 0 ? 0 : fullName.indexOf(">") + 1;
		int endIndex = fullName.lastIndexOf(">") < 0 ? 0 : fullName.lastIndexOf(">");
		String old = fullName.substring(beginIndex, endIndex);
		String NewFullName = fullName.replaceFirst(old, name);
		return NewFullName;
	}

	@Override
	public ResultVO findbyid(String id) {
		ResultVO result = new ResultVO();
		SystemType type = systemTypeDAO.query(id);
		if (type == null) {
			throw new SystemTypeNotFoundException("该分类未找到");
		}
		result.setData(type);
		return result;
	}

	@Override
	public ResultVO updateTypeImage(SystemTypeEditVO typeEditVO) {
		ResultVO result=new ResultVO();
		SystemType type=new SystemType();
		BeanUtils.copyProperties(typeEditVO, type);
		systemTypeDAO.update(type);
		
		if(StringUtils.isNotBlank(typeEditVO.getImgUrl())){
			FileUtil.moveFile(uploadPath + typeEditVO.getImgUrl(), typePath);
		}
		
		result.setData(type);
		return result;
	}

	@Override
	public ResultVO deleteTypeImage(String id) {
		ResultVO result=new ResultVO();
		SystemType type=systemTypeDAO.query(id);
		if (type == null) {
			throw new SystemTypeNotFoundException("该分类未找到");
		}
		if(StringUtils.isNotBlank(type.getImgUrl())){
			FileUtil.removeFile(typePath+type.getImgUrl());
		}
		type.setImgUrl(null);
		systemTypeDAO.update(type,true);
		result.setData(type);
		return result;
	}

	@Override
	public ResultVO getGoodsByType(String id) {
		ResultVO result=new ResultVO();
		List<GoodsInfoBO> list = systemTypeDAO.getGoodsByType(id,ShopIsPlatform.OWN.toIntStatus());
		result.setData(list);
		return result;
	}
	
}